package com.wuyi.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wuyi.mapper.*;
import com.wuyi.pojo.*;
import com.wuyi.pojo.bo.PostBO;
import com.wuyi.pojo.vo.*;
import com.wuyi.service.FileUploadService;
import com.wuyi.service.PostService;
import com.zc.enums.CommentEnum;
import com.zc.enums.YesOrNo;
import com.zc.utils.JSONResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 曾川
 * @version 1.0.0
 * @ClassName PostServiceImpl.java
 * @Description 帖子实现类
 * @createTime 2021年11月03日 20:20:00
 */
@Service
public class PostServiceImpl implements PostService {

    public final static Logger logger = LoggerFactory.getLogger(PostServiceImpl.class);


    @Autowired
    private PostMapper postMapper;
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private PostMapperCustom postMapperCustom;
    @Autowired
    private CommentMapperCustom mapperCustom;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CollectMapper collectMapper;
    @Autowired
    private FollowMapper followMapper;
    @Autowired
    private CollectMapperCustom collectMapperCustom;
    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    private FileUploadService fileUploadService;


    /**
     * 发布帖子
     * @param postBO
     * @return
     */
    @Transactional( propagation = Propagation.REQUIRED)
    @Override
    public JSONResult addPost(PostBO postBO) throws IOException {

        String fileFinalPath = "";
        if (null != postBO.getPostImage() && postBO.getPostImage().length > 0) {
            MultipartFile[] files = postBO.getPostImage();
            String[] filePaths = new String[files.length];
            int i = 0;
            //开始上传文件
            if (files.length > 0 && null != files ) {
                for (MultipartFile file : files) {
                    /*logger.info(file.getOriginalFilename());
                    String filesName = file.getOriginalFilename();
                    //截取后缀名
                    int fileOf = filesName.lastIndexOf(".");
                    String fileType1 = filesName.substring(fileOf + 1);
                    logger.info("-----------当前文件格式为：" + fileType1);

                    String filePath = "D:/wuyi-resource/post/" + postBO.getPostUid() + "/" + new Date().getTime() +"-" + filesName;
//                    String filePath = uploadPath+ "/post/" + postBO.getPostUid() + "/" + new Date().getTime() +"-" + filesName;

                    File newFile1 = new File(filePath);
                    if (null != newFile1.getParentFile()) {
                        //创建文件夹
                        newFile1.getParentFile().mkdirs();
                    }

                    try {
                        file.transferTo(newFile1);
                        filePaths[i++] = filePath;
                    } catch (IOException e) {
                        e.printStackTrace();
                        return  JSONResult.errorMsg("上传文件失败");
                    }

                     */

                    String postPath = fileUploadService.upload(file, postBO.getPostUid(), "post");
                    filePaths[i++] = postPath;
                }
            }

            //调用service插入数据
            StringBuilder sb = new StringBuilder();
            for (String f : filePaths) {
                sb.append(f).append(",");
                logger.info("------------资源文件路径" + f);
            }

            logger.info("fileFinalPath--------------:"+ sb.substring(0,sb.length() - 1));
            fileFinalPath = sb.substring(0,sb.length() - 1);
        }


//        MultipartFile postImage = postBO.getPostImage();
//        //存到数据库的封面图片路径
//        String imgPath = "";
//        //存到数据库的文件路径
//        int i = 0;
//        //开始上传图片文件
//        if (!postImage.isEmpty()) {
//            //源文件名
//            String originalFilename = postImage.getOriginalFilename();
//            //截取后缀名
//            int lastIndexOf = originalFilename.lastIndexOf(".");
//            String fileType = originalFilename.substring(lastIndexOf + 1);
//            logger.info("-----------当前文件格式为：" + fileType);
//            //如果不是图片，则直接return
//            if (fileType.equals("jpg") || fileType.equals("png") || fileType.equals("jpeg")) {
//
//                imgPath = "D:/wuyi-resource/post/" +  postBO.getPostUid() + "/" + new Date().getTime() +"-" +  originalFilename;
//
//                File newFile = new File(imgPath);
//
//                if (newFile.getParentFile() != null) {
//                    //创建文件夹
//                    newFile.getParentFile().mkdirs();
//                }
//
//                try {
//                    postImage.transferTo(newFile);
//
//                } catch (IOException e) {
//                    e.printStackTrace();
//                    return JSONResult.errorMsg("上传封面图片失败");
//                }
//            }else{
//                return JSONResult.errorMsg("图片格式不正确！");
//            }
//        }



        Post post = new Post();
        BeanUtils.copyProperties(postBO, post);
//        post.setPostImage(imgPath);
        post.setPostImage(fileFinalPath);
        post.setPostHot(CommentEnum.DEFAULT_HOT.type);
        post.setPostTime(new Date());
        post.setCreateTime(new Date());
        post.setUpdateTime(new Date());

        int res = postMapper.insert(post);
        if (res != 1) {
            return JSONResult.errorMsg("发布帖子失败!");
        }
        return JSONResult.ok("发布帖子成功");
    }

    /**
     * 查询交流区列表
     *
     * @return
     */
    @Transactional( propagation = Propagation.SUPPORTS)
    @Override
    public PageInfo  postList(Integer pageNum, Integer pageSize) {
        List<Post> postList = postMapper.selectAll();
        PageHelper.startPage(pageNum,pageSize);
        List<Post> collect = postList.stream().sorted(
                Comparator.comparing(Post::getCreateTime).reversed()).
                collect(Collectors.toList());
        PageInfo pageInfo = new PageInfo<>(collect);
        pageInfo.setList(collect);
        return pageInfo;
    }

    /**
     * 根据帖子id查询帖子详情
     *
     * @param postId
     * @return
     */
//    @Transactional( propagation = Propagation.SUPPORTS)
//    @Override
//    public List<PostDetailsVO> queryPostDetails(Integer postId) {
//
//        return postMapperCustom.getPostDeatils(postId);
//    }

    @Transactional( propagation = Propagation.SUPPORTS)
    @Override
    public PostDetailsVO selectPostDetails(Integer postId) {


        //根据id查询帖子信息
        Example example = new Example(Post.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("postId", postId);
        Post post = postMapper.selectOneByExample(example);
        //根据帖子id查询相应的评论列表
        Example example1 = new Example(Comment.class);
        Example.Criteria criteria1 = example1.createCriteria();
        criteria1.andEqualTo("commentPid",postId);

        User newUser = new User();
        newUser.setUserName(post.getPostUid());
        User newUser2 = userMapper.selectOne(newUser);


        List<Comment> comments = commentMapper.selectByExample(example1);
        List<CommentVO> commentVOList = new ArrayList<>();
        //设置返回类
        PostDetailsVO postDetailsVO = new PostDetailsVO();
        postDetailsVO.setPostId(post.getPostId());
//        postDetailsVO.setPostUid(post.getPostUid());
        postDetailsVO.setPostUid(newUser2.getUserId());
        postDetailsVO.setPostUserName(newUser2.getUserName());
        postDetailsVO.setPostText(post.getPostText());
        postDetailsVO.setPostTitle(post.getPostTitle());
        postDetailsVO.setPostHot(post.getPostHot());
        postDetailsVO.setIsAnonymous(post.getIsAnonymous());
//        postDetailsVO.setPostImage(post.getPostImage());
        postDetailsVO.setCreateTime(post.getCreateTime());

        //查询用户信息，将相应的评论人的头像set给评论vo
        List<User> users = userMapper.selectAll();

        //设置发帖用户的头像
        for (User user : users) {
            if (user.getUserName().equals(post.getPostUid())) {
                postDetailsVO.setPostUserFace(user.getUserFace());
                break;
            }
        }

        for (Comment comment : comments) {
            CommentVO commentVO = new CommentVO();
            commentVO.setCommentId(comment.getCommentId());
            commentVO.setCommentPid(comment.getCommentPid());
            commentVO.setCommentUid(comment.getCommentUid());

            //这里设置评论的头像
            for (User user : users) {
                if (comment.getCommentUid().equals(user.getUserName())) {
                    commentVO.setUserFace(user.getUserFace());
                    break;
                }

            }
            commentVO.setCommentText(comment.getCommentText());
            commentVO.setCreateTime(comment.getCreateTime());
            commentVOList.add(commentVO);
        }

        postDetailsVO.setCommentVOList(commentVOList);


        //执行热度更新
        post.setPostHot(post.getPostHot() + 1);
        post.setUpdateTime(new Date());
        postMapper.updateByPrimaryKeySelective(post);
//        postDetailsVO.setTest(post.getPostImage().split(","));
        postDetailsVO.setPostImage(post.getPostImage().split(","));

        return postDetailsVO;
    }

    /**
     * 帖子页面查询个人信息
     *
     * @param userId
     * @return
     */
    @Transactional( propagation = Propagation.SUPPORTS)
    @Override
    public CenterUserInfoVO queryUserInfo(String userId, String userName) {

        CenterUserInfoVO userInfoVO = new CenterUserInfoVO();

        //1.先查询个人信息
        User user = new User();
        user.setUserId(userId);
        User user1 = userMapper.selectOne(user);
        BeanUtils.copyProperties(user1, userInfoVO);
        userInfoVO.setUserRole(user1.getUserRole());

        //2.计算个人发起帖子数   个人粉丝数   个人关注数
        Post post = new Post();
        post.setPostUid(user1.getUserName());
        int postNum = postMapper.selectCount(post);
        userInfoVO.setPostNum(postNum);

        //计算粉丝数
        Follow follow = new Follow();
        follow.setFollowedUid(user1.getUserName());
        int fansNum = followMapper.selectCount(follow);
        userInfoVO.setFansNum(fansNum);
        //计算关注数
        Follow follow2 = new Follow();
        follow2.setFollowUid(user1.getUserName());
        int followNum = followMapper.selectCount(follow2);
        userInfoVO.setFollowNum(followNum);

        //判断是否已关注
        userInfoVO.setIsFollowed(YesOrNo.NO.type);
        if (null != userName) {
            Follow follow3 = new Follow();
            follow3.setFollowUid(userName);
            follow3.setFollowedUid(user1.getUserName());
            int i = followMapper.selectCount(follow3);
            if (i == 1) userInfoVO.setIsFollowed(YesOrNo.YES.type);
        }

        //3.收藏的记录数  资料上传的记录数
        Map<String, Object> map = new HashMap<>();
        map.put("userId", user1.getUserName());
        map.put("categoryId", 1);

        //收藏的记录数
        //计算收藏资料数
        int collectMatNum = collectMapperCustom.getMyCollectCounts(map);
        userInfoVO.setCollectMatNum(collectMatNum);
        //计算收藏课件数
        map.put("categoryId", 2);
        int collectCouNum = collectMapperCustom.getMyCollectCounts(map);
        userInfoVO.setCollectCouNum(collectCouNum);
        //计算收藏软件数
        map.put("categoryId", 3);
        int collectSofNum = collectMapperCustom.getMyCollectCounts(map);
        userInfoVO.setCollectSofNum(collectSofNum);

        //资料上传的记录数
        //计算上传资料数
        Resource resource = new Resource();
        resource.setResourceUid(user1.getUserName());
        resource.setResourceCid(1);
        int resourceMatNum = resourceMapper.selectCount(resource);
        userInfoVO.setResourceMatNum(resourceMatNum);
        //计算上传课件数
        resource.setResourceCid(2);
        int resourceCouNum = resourceMapper.selectCount(resource);
        userInfoVO.setResourceCouNum(resourceCouNum);
        //计算上传软件数
        resource.setResourceCid(3);
        int resourceSofNum = resourceMapper.selectCount(resource);
        userInfoVO.setResourceSofNum(resourceSofNum);

        return userInfoVO;
    }

    /**
     * 查询个人发布的帖子
     *
     * @param userId
     * @return
     */
    @Transactional( propagation = Propagation.SUPPORTS)
    @Override
    public PageInfo queryPostList(String userId, Integer pageNum, Integer pageSize) {

        PageHelper.startPage(pageNum, pageSize);
        Example example = new Example(Post.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("postUid",userId);

        List<Post> posts = postMapper.selectByExample(example);

        PageInfo pageInfo = new PageInfo<>(posts);
        pageInfo.setList(posts);
        return pageInfo;
    }

    /**
     * 删除帖子
     *
     * @param postId
     */
    @Transactional( propagation = Propagation.REQUIRED)
    @Override
    public void deletePost(Integer postId) {
        //删除帖子的同时，将相应的评论删除
        //1.删除帖子
        postMapper.deleteByPrimaryKey(postId);
        //2.删除与帖子相关的评论
        Example example = new Example(Comment.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("commentPid", postId);
        List<Comment> comments = commentMapper.selectByExample(example);
        if (comments.size() > 0) {
            for (Comment comment : comments) {
                commentMapper.delete(comment);
            }
        }

    }

    /**
     * 按热度降序查询帖子
     *
     * @return
     */
    @Override
    public PageInfo recommendList(Integer pageNum, Integer pageSize) {

        PageHelper.startPage(pageNum, pageSize);
        Example example = new Example(Post.class);
        example.orderBy("postHot").desc();
        List<Post> postList = postMapper.selectByExample(example);
        List<PostRecommendVO> postRecommendVOS = new ArrayList<>();
        for (Post post : postList) {
            PostRecommendVO postRecommendVO = new PostRecommendVO();
            BeanUtils.copyProperties(post, postRecommendVO);
            postRecommendVOS.add(postRecommendVO);
        }

        PageInfo pageInfo = new PageInfo<>(postRecommendVOS);
        pageInfo.setList(postRecommendVOS);

        return pageInfo;
    }

    /**
     * 按评论数多少降序查询帖子
     *
     * @param pageNum
     * @param pageSize
     */
    @Override
    public PageInfo answerList(Integer pageNum, Integer pageSize) {

        List<PostRecommendVO> postRecommendVOS = new ArrayList<>();
        //查出所有的帖子
        List<Post> postList = postMapper.selectAll();
        //计算评论数最多的帖子
        List<CommentCountVO> myCommentCounts = mapperCustom.getMyCommentCounts();
        //分页
        PageHelper.startPage(pageNum, pageSize);
        //遍历赋值
        for (CommentCountVO myCommentCount : myCommentCounts) {
            for (Post post : postList) {
                if (myCommentCount.getCommentPid().equals(post.getPostId())) {
                    PostRecommendVO postRecommendVO = new PostRecommendVO();
                    BeanUtils.copyProperties(post, postRecommendVO);
                    postRecommendVOS.add(postRecommendVO);
                }

            }
        }
        //设置分页
        PageInfo pageInfo = new PageInfo<>(postRecommendVOS);
        pageInfo.setList(postRecommendVOS);

        return pageInfo;
    }


}
